﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic;

namespace V5_Common {
    /// <summary>
    /// 字符串操作封装
    /// </summary>
    public class StringHelper {
        private static readonly StringHelper m_Instance = new StringHelper();
        /// <summary>
        /// 
        /// </summary>
        public static StringHelper Instance {
            get { return m_Instance; }
        }
        /// <summary>
        /// 
        /// </summary>
        public StringHelper() {

        }

        /// <summary>
        /// 转化成数字
        /// </summary>
        /// <param name="oValue"></param>
        /// <returns></returns>
        public int SetNumber(object oValue) {
            return Convert.ToInt32("0" + oValue);
        }
        /// <summary>
        /// 转化为字符
        /// </summary>
        /// <param name="oValue"></param>
        /// <returns></returns>
        public string SetString(object oValue) {
            return Convert.ToString("" + oValue);
        }
        /// <summary>
        /// 转化为字符
        /// </summary>
        /// <param name="oValue"></param>
        /// <param name="sqlSafeCheck"></param>
        /// <returns></returns>
        public string SetString(object oValue, bool sqlSafeCheck) {
            string tempString = SetString(oValue);
            if (sqlSafeCheck && Easp.Validator.IsSafeSqlString(tempString)) {
                return "unsafe string";
            }
            return tempString;
        }
        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public bool IsBrowserGet() {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++) {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0) {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public bool IsSearchEnginesGet() {
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++) {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0) {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public string GetIP() {
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty) {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (null == result || result == String.Empty) {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (null == result || result == String.Empty || !IsIP(result)) {
                return "0.0.0.0";
            }
            return result;
        }
        #region Ip类

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool IsIP(string ip) {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        #endregion

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string CutStr(string str, int length) {
            return CutStr(str, length, false);
        }
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <param name="flg"></param>
        /// <returns></returns>
        public string CutStr(string str, int length, bool flg) {
            int i = 0, j = 0;
            foreach (char chr in str) {
                if ((int)chr > 127) {
                    i += 2;
                }
                else {
                    i++;
                }
                if (i > length) {
                    str = str.Substring(0, j);
                    if (flg)
                        str += "...";
                    break;
                }
                j++;
            }
            return str;
        }


        /// <summary>
        /// 删除首尾指定的字符串
        /// </summary>
        /// <param name="strContent">需要删除的字符文本</param>
        /// <param name="delStr">删除字符串</param>
        /// <returns></returns>
        public string DelHeadAndEndStr(string strContent, string delStr) {
            if (strContent.Trim() == "" || strContent.Length == 0) {
                return "";
            }
            if (strContent.Substring(0, 1) == delStr) {
                strContent = strContent.Substring(1);
            }
            if (strContent.LastIndexOf(delStr) > 0) {
                strContent = strContent.Substring(0, strContent.Length - 1);
            }
            return strContent;
        }

        /// <summary>
        /// 不区分大小写替换
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="oldStr">被替换的字符串</param>
        /// <param name="newStr">目标替换字符串</param>
        /// <returns></returns>
        public string Replace(string source, string oldStr, string newStr) {
            return Strings.Replace(source, oldStr, newStr, 1, -1, CompareMethod.Text);
            //return Regex.Replace(source, oldStr, newStr, RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent">要分割的字符串</param>
        /// <param name="strSplit">分割标签</param>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit) {
            if (!string.IsNullOrEmpty(strContent)) {
                if (strContent.IndexOf(strSplit) < 0)
                    return new string[] { strContent };
                return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
            }
            else
                return new string[0] { };
        }
        /// <summary>
        /// 不区分大小写的替换
        /// </summary>
        /// <param name="original">原字符串</param>
        /// <param name="pattern">需替换字符</param>
        /// <param name="replacement">被替换内容</param>
        /// <returns></returns>
        public string ReplaceEx(string original, string pattern, string replacement) {
            int count, position0, position1;
            count = position0 = position1 = 0;
            string upperString = original.ToUpper();
            string upperPattern = pattern.ToUpper();
            int inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);
            char[] chars = new char[original.Length + Math.Max(0, inc)];
            while ((position1 = upperString.IndexOf(upperPattern, position0)) != -1) {
                for (int i = position0; i < position1; ++i) chars[count++] = original[i];
                for (int i = 0; i < replacement.Length; ++i) chars[count++] = replacement[i];
                position0 = position1 + pattern.Length;
            }
            if (position0 == 0) return original;
            for (int i = position0; i < original.Length; ++i) chars[count++] = original[i];
            return new string(chars, 0, count);
        }

        /// <summary>
        /// 得到字符串长度，一个汉字长度为2
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        public static int StrLength(string inputString) {
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            int tempLen = 0;
            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++) {
                if ((int)s[i] == 63)
                    tempLen += 2;
                else
                    tempLen += 1;
            }
            return tempLen;
        }

        public string ParseTags(string HTMLStr) {
            return Regex.Replace(HTMLStr, "<[^>]*>", "");
        }


        /// <summary>
        /// HtmlEncode
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string HtmlEncode(string content) {
            return HttpContext.Current.Server.HtmlEncode(content);
        }

        /// <summary>
        ///  HtmlDecode
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string HtmlDecode(string content) {
            return HttpContext.Current.Server.HtmlDecode(content);
        }

        #region 返回指定字符串的单字节长度
        /// <summary>
        /// 返回指定字符串的单字节长度
        /// </summary>
        /// <param name="strInPut"></param>
        /// <returns></returns>
        public static int Length(string strInPut) {
            Encoding encoding = Encoding.Default;
            byte[] strbytes = encoding.GetBytes(strInPut);
            return strbytes.Length;
        }
        #endregion

        #region  截短字串的函数，分区中英文
        /// <summary>
        /// 截短字串的函数
        /// </summary>
        /// <param name="mText">要加工的字串</param>
        /// <param name="byteCount">长度</param>
        /// <returns>被加工过的字串</returns>
        public static string Left(string mText, int byteCount) {
            if (byteCount < 1) return mText;

            if (System.Text.Encoding.Default.GetByteCount(mText) <= byteCount) {
                return mText;
            }
            else {
                byte[] txtBytes = System.Text.Encoding.Default.GetBytes(mText);
                byte[] newBytes = new byte[byteCount - 4];

                for (int i = 0; i < byteCount - 4; i++) {
                    newBytes[i] = txtBytes[i];
                }

                return System.Text.Encoding.Default.GetString(newBytes) + "...";
            }
        }
        #endregion

        #region  截短字串的函数，不分区中英文
        /// <summary>
        /// 截短字串的函数，不分区中英文
        /// </summary>
        /// <param name="InPut"></param>
        /// <param name="Long"></param>
        /// <returns></returns>
        public static string Left(object InPut, int Long) {
            if (Long >= InPut.ToString().Length) {
                return InPut.ToString();
            }
            else {
                return InPut.ToString().Substring(0, Long - 3) + "...";
            }
        }
        #endregion

        #region 去除非法字串
        /// <summary>
        /// 去除非法字串
        /// </summary>
        /// <param name="InPut">原字串</param>
        /// <returns>过滤过的字串</returns>
        public static string ReplaceBadChar(string InPut) {
            if (InPut.Trim() == "") {
                return "";
            }
            else {
                StringBuilder OutPut = new StringBuilder();
                OutPut.Append(InPut);
                OutPut.Replace("'", "");
                OutPut.Replace("*", "");
                OutPut.Replace("?", "");
                OutPut.Replace("(", "");
                OutPut.Replace(")", "");
                OutPut.Replace("<", "");
                OutPut.Replace("=", "");

                return OutPut.ToString().Trim();
            }
        }
        #endregion
        /// <summary>
        /// 转义SQL中的限制符号
        /// </summary>
        /// <param name="InPut"></param>
        /// <returns></returns>
        public static string SQL_ESC(string InPut) {
            StringBuilder OutPut = new StringBuilder();
            OutPut.Append(InPut);
            OutPut.Replace("[", "[[]");
            OutPut.Replace("%", "[%]");
            OutPut.Replace("_", "[_]");
            OutPut.Replace("'", "''");

            return OutPut.ToString().Trim();
        }

        #region 过滤指定的关键字
        /// <summary>
        /// 过滤指定的关键字
        /// </summary>
        /// <param name="InPut"></param>
        /// <param name="badwords"></param>
        /// <returns></returns>
        public static string FilterBadWords(string InPut, string badwords) {
            string[] tempstr = badwords.Split('|');

            StringBuilder OutPut = new StringBuilder();
            OutPut.Append(InPut);
            for (int i = 0; i < tempstr.Length; i++) {
                if (tempstr[i].Length > 0) {
                    OutPut.Replace(tempstr[i], new string('*', tempstr[i].Length));
                }
            }
            return OutPut.ToString();
        }
        #endregion

        /// <summary>
        /// 移除Html 并截取字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public string CutStrForRHtml(string str, int len) {
            str = Easp.Html.ParseTags(str);
            str = CutStr(str, len);
            return str;
        }

    }
}
